// navigation.js
class PrototypeNavigation {
  constructor() {
    this.currentPage = 'login';
    // 初始状态根据屏幕尺寸设置
    this.isNavOpen = window.innerWidth > 768;
    this.init();
  }
  
  init() {
    this.bindEvents();
    this.loadPage(this.currentPage);
    this.createOverlay();
    this.initTriggerButton();
  }
  
  bindEvents() {
    // 导航链接点击
    document.querySelectorAll('.nav-link').forEach(link => {
      link.addEventListener('click', (e) => {
        e.preventDefault();
        const page = link.dataset.page;
        this.navigateToPage(page);
      });
    });
    
    // 导航切换按钮
    const navToggle = document.querySelector('.nav-toggle');
    const navTrigger = document.querySelector('.nav-trigger');
    
    if (navToggle) {
      navToggle.addEventListener('click', (e) => {
        console.log('Nav toggle clicked, current state:', this.isNavOpen);
        this.toggleNav();
      });
    }
    
    if (navTrigger) {
      navTrigger.addEventListener('click', (e) => {
        console.log('Nav trigger clicked');
        this.openNav();
      });
    }
    
    // 遮罩层点击关闭
    const overlay = document.querySelector('.nav-overlay');
    if (overlay) {
      overlay.addEventListener('click', () => this.closeNav());
    }
    
    // 键盘快捷键
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape') {
        this.closeNav();
      }
    });
    
    // 窗口大小改变时调整导航状态
    window.addEventListener('resize', () => {
      this.handleResize();
    });
  }
  
  createOverlay() {
    let overlay = document.querySelector('.nav-overlay');
    if (!overlay) {
      overlay = document.createElement('div');
      overlay.className = 'nav-overlay';
      document.body.appendChild(overlay);
      console.log('Overlay created successfully');
      
      // 绑定遮罩层点击事件
      overlay.addEventListener('click', () => this.closeNav());
    }
    return overlay;
  }
  
  // 获取所有导航相关的DOM元素
  getNavElements() {
    return {
      nav: document.querySelector('.prototype-nav'),
      main: document.querySelector('.prototype-main'),
      overlay: document.querySelector('.nav-overlay'),
      navTrigger: document.querySelector('.nav-trigger')
    };
  }
  
  initTriggerButton() {
    const navTrigger = document.querySelector('.nav-trigger');
    if (!navTrigger) {
      console.warn('Nav trigger button not found. Some navigation features may not work.');
      return;
    }
    
    // 初始状态：桌面端导航默认显示，所以隐藏触发按钮
    if (window.innerWidth > 768 && this.isNavOpen) {
      navTrigger.classList.remove('show');
    } else if (window.innerWidth > 768 && !this.isNavOpen) {
      navTrigger.classList.add('show');
    }
  }
  
  navigateToPage(page) {
    if (page === this.currentPage) return;
    
    this.setActiveNavItem(page);
    this.loadPage(page);
    this.currentPage = page;
    
    // 移动端自动关闭导航
    if (window.innerWidth <= 768) {
      this.closeNav();
    }
  }
  
  setActiveNavItem(page) {
    document.querySelectorAll('.nav-link').forEach(link => {
      link.classList.remove('active');
    });
    
    const activeLink = document.querySelector(`[data-page="${page}"]`);
    if (activeLink) {
      activeLink.classList.add('active');
    }
  }
  
  async loadPage(page, animation = 'fade') {
    const container = document.getElementById('page-container');
    if (!container) return;
    
    // 添加退出动画
    if (animation === 'fade') {
      container.classList.add('page-fade-exit-active');
    }
    
    // 等待退出动画完成
    await new Promise(resolve => setTimeout(resolve, 200));
    
    // 显示加载状态
    container.classList.add('loading');
    
    try {
      const response = await fetch(`pages/${page}.html`);
      if (response.ok) {
        const html = await response.text();
        container.innerHTML = html;
        
        // 移除加载和退出状态
        container.classList.remove('loading', 'page-fade-exit-active');
        
        // 添加进入动画
        if (animation === 'fade') {
          container.classList.add('page-fade-enter');
          // 触发重绘
          container.offsetHeight;
          container.classList.add('page-fade-enter-active');
          container.classList.remove('page-fade-enter');
        }
        
        // 触发页面加载完成事件
        this.onPageLoaded(page);
      } else {
        container.innerHTML = `
          <div class="page-content">
            <div class="page-header">
              <h1>页面加载失败</h1>
              <p>请检查网络连接后重试</p>
            </div>
            <div class="page-body u-text-center">
              <button class="c-button c-button--primary" onclick="location.reload()">
                重新加载
              </button>
            </div>
          </div>
        `;
      }
    } catch (error) {
      container.innerHTML = `
        <div class="page-content">
          <div class="page-header">
            <h1>网络错误</h1>
            <p>无法连接到服务器</p>
          </div>
          <div class="page-body u-text-center">
            <button class="c-button c-button--primary" onclick="location.reload()">
              重新尝试
            </button>
          </div>
        </div>
      `;
    } finally {
      // 清理动画类
      setTimeout(() => {
        container.classList.remove('page-fade-enter-active');
      }, 300);
    }
  }
  
  onPageLoaded(page) {
    // 执行页面特定的初始化逻辑
    console.log(`页面 ${page} 加载完成`);
    
    // 初始化页面特定的交互逻辑
    this.initPageInteractions(page);
    
    // 重新初始化Feather图标
    if (typeof feather !== 'undefined') {
      feather.replace();
    }
  }
  
  initPageInteractions(page) {
    switch (page) {
      case 'login':
        this.initLoginPage();
        break;
      case 'about':
        this.initAboutPage();
        break;
      default:
        break;
    }
  }
  
  initLoginPage() {
    // 登录页面特定的交互逻辑
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
      loginForm.addEventListener('submit', (e) => {
        e.preventDefault();
        this.handleLogin();
      });
    }
    
    // 输入框实时验证
    const inputs = document.querySelectorAll('.c-input');
    inputs.forEach(input => {
      input.addEventListener('blur', () => this.validateInput(input));
      input.addEventListener('input', () => this.clearValidationError(input));
    });
  }
  
  initAboutPage() {
    // 关于我们页面特定的交互逻辑
    const contactButtons = document.querySelectorAll('[data-contact]');
    contactButtons.forEach(button => {
      button.addEventListener('click', (e) => {
        const contactType = e.target.dataset.contact;
        this.handleContact(contactType);
      });
    });
  }
  
  handleLogin() {
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const loginButton = document.querySelector('#login-form .c-button--primary');
    
    // 基本验证
    if (!this.validateInput(emailInput) || !this.validateInput(passwordInput)) {
      return;
    }
    
    // 显示加载状态
    const originalText = loginButton.textContent;
    loginButton.innerHTML = '<div class="c-spinner"></div> 登录中...';
    loginButton.disabled = true;
    
    // 模拟登录请求
    setTimeout(() => {
      // 恢复按钮状态
      loginButton.textContent = originalText;
      loginButton.disabled = false;
      
      // 显示成功消息
      this.showMessage('登录成功！', 'success');
    }, 2000);
  }
  
  validateInput(input) {
    const value = input.value.trim();
    const inputGroup = input.closest('.c-input-group');
    let errorMessage = '';
    
    // 移除之前的错误状态
    input.classList.remove('c-input--error');
    const existingError = inputGroup.querySelector('.c-error-message');
    if (existingError) {
      existingError.remove();
    }
    
    // 验证规则
    switch (input.type) {
      case 'email':
        if (!value) {
          errorMessage = '请输入邮箱地址';
        } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
          errorMessage = '请输入有效的邮箱地址';
        }
        break;
      case 'password':
        if (!value) {
          errorMessage = '请输入密码';
        } else if (value.length < 6) {
          errorMessage = '密码至少需要6个字符';
        }
        break;
      default:
        if (input.required && !value) {
          errorMessage = '此字段为必填项';
        }
        break;
    }
    
    // 显示错误信息
    if (errorMessage) {
      input.classList.add('c-input--error');
      const errorElement = document.createElement('div');
      errorElement.className = 'c-error-message';
      errorElement.textContent = errorMessage;
      inputGroup.appendChild(errorElement);
      return false;
    }
    
    return true;
  }
  
  clearValidationError(input) {
    input.classList.remove('c-input--error');
    const inputGroup = input.closest('.c-input-group');
    const errorMessage = inputGroup.querySelector('.c-error-message');
    if (errorMessage) {
      errorMessage.remove();
    }
  }
  
  handleContact(contactType) {
    let message = '';
    switch (contactType) {
      case 'email':
        message = '邮箱已复制到剪贴板';
        navigator.clipboard?.writeText('contact@example.com');
        break;
      case 'phone':
        message = '电话号码已复制到剪贴板';
        navigator.clipboard?.writeText('+86 138 0013 8000');
        break;
      case 'website':
        window.open('https://example.com', '_blank');
        message = '正在打开官方网站';
        break;
      default:
        message = '功能开发中';
        break;
    }
    this.showMessage(message, 'success');
  }
  
  showMessage(text, type = 'info') {
    // 创建消息提示
    const message = document.createElement('div');
    message.className = `message message--${type}`;
    message.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 3000;
      padding: 12px 16px;
      background: ${type === 'success' ? '#10B981' : type === 'error' ? '#EF4444' : '#007AFF'};
      color: white;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
      transform: translateX(100%);
      transition: transform 0.3s ease;
    `;
    message.textContent = text;
    
    document.body.appendChild(message);
    
    // 显示动画
    setTimeout(() => {
      message.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
      message.style.transform = 'translateX(100%)';
      setTimeout(() => {
        document.body.removeChild(message);
      }, 300);
    }, 3000);
  }
  
  toggleNav() {
    console.log('toggleNav called, current isNavOpen:', this.isNavOpen);
    if (this.isNavOpen) {
      console.log('Calling closeNav');
      this.closeNav();
    } else {
      console.log('Calling openNav');
      this.openNav();
    }
  }
  
  openNav() {
    const nav = document.querySelector('.prototype-nav');
    const main = document.querySelector('.prototype-main');
    const overlay = document.querySelector('.nav-overlay');
    const navTrigger = document.querySelector('.nav-trigger');
    
    // 检查核心元素是否存在
    if (!nav || !main) {
      console.error('openNav: Required elements not found', {
        nav: !!nav,
        main: !!main
      });
      return;
    }
    
    if (window.innerWidth <= 768) {
      // 移动端：使用 nav-open 类
      nav.classList.add('nav-open');
      nav.classList.remove('nav-hidden');
      if (overlay) overlay.classList.add('active');
    } else {
      // 桌面端：移除 nav-hidden 类
      nav.classList.remove('nav-hidden');
      main.classList.remove('nav-hidden');
      // 隐藏触发按钮
      if (navTrigger) navTrigger.classList.remove('show');
    }
    
    this.isNavOpen = true;
  }
  
  closeNav() {
    console.log('closeNav called, screen width:', window.innerWidth);
    const nav = document.querySelector('.prototype-nav');
    const main = document.querySelector('.prototype-main');
    const overlay = document.querySelector('.nav-overlay');
    const navTrigger = document.querySelector('.nav-trigger');
    
    // 检查核心元素是否存在
    if (!nav || !main) {
      console.error('closeNav: Required elements not found', {
        nav: !!nav,
        main: !!main
      });
      return;
    }
    
    if (window.innerWidth <= 768) {
      console.log('Mobile: removing nav-open');
      // 移动端：移除 nav-open 类，但不添加 nav-hidden
      nav.classList.remove('nav-open');
      overlay.classList.remove('active');
    } else {
      console.log('Desktop: adding nav-hidden');
      // 桌面端：添加 nav-hidden 类
      nav.classList.add('nav-hidden');
      main.classList.add('nav-hidden');
      // 显示触发按钮
      if (navTrigger) navTrigger.classList.add('show');
    }
    
    this.isNavOpen = false;
    console.log('Nav closed, isNavOpen set to:', this.isNavOpen);
  }
  
  resetNavForDesktop() {
    const nav = document.querySelector('.prototype-nav');
    const main = document.querySelector('.prototype-main');
    const overlay = document.querySelector('.nav-overlay');
    const navTrigger = document.querySelector('.nav-trigger');
    
    // 检查核心元素是否存在
    if (!nav || !main) {
      console.error('resetNavForDesktop: Required elements not found', {
        nav: !!nav,
        main: !!main
      });
      return;
    }
    
    // 清理所有状态类
    nav.classList.remove('nav-open');
    nav.classList.remove('nav-hidden');
    main.classList.remove('nav-hidden');
    if (overlay) overlay.classList.remove('active');
    // 桌面端默认显示导航时隐藏触发按钮
    if (navTrigger) navTrigger.classList.remove('show');
    
    this.isNavOpen = true;
  }
  
  // 窗口大小改变时重置导航状态
  handleResize() {
    const navTrigger = document.querySelector('.nav-trigger');
    
    if (window.innerWidth > 768) {
      // 切换到桌面端时，重置导航状态
      this.resetNavForDesktop();
    } else {
      // 切换到移动端时，确保导航处于正确的初始状态
      const nav = document.querySelector('.prototype-nav');
      const main = document.querySelector('.prototype-main');
      const overlay = document.querySelector('.nav-overlay');
      
      // 检查元素是否存在
      if (!nav || !main) {
        console.error('handleResize: Required elements not found', {
          nav: !!nav,
          main: !!main
        });
        return;
      }
      
      nav.classList.remove('nav-hidden');
      main.classList.remove('nav-hidden');
      // 移动端始终显示触发按钮（由CSS控制）
      if (navTrigger) navTrigger.classList.remove('show');
      
      if (!this.isNavOpen) {
        nav.classList.remove('nav-open');
        if (overlay) overlay.classList.remove('active');
      }
    }
  }
}

// 初始化导航
document.addEventListener('DOMContentLoaded', () => {
  // 确保核心元素存在后再初始化
  const requiredElements = [
    '.prototype-nav',
    '.prototype-main'
  ];
  
  // 检查可选元素
  const optionalElements = [
    '.nav-trigger'
  ];
  
  const coreElementsExist = requiredElements.every(selector => {
    const element = document.querySelector(selector);
    if (!element) {
      console.error(`Required element not found: ${selector}`);
      return false;
    }
    return true;
  });
  
  // 检查可选元素（只是警告，不阻止初始化）
  optionalElements.forEach(selector => {
    const element = document.querySelector(selector);
    if (!element) {
      console.warn(`Optional element not found: ${selector}. Some features may not work.`);
    }
  });
  
  if (coreElementsExist) {
    window.prototypeNav = new PrototypeNavigation();
  } else {
    console.error('Required DOM elements are missing. Navigation initialization failed.');
  }
}); 